/**
 * 设置控制器
 * 处理应用设置和配置相关的数据库操作
 */

import { BaseController, ensureDbInit, createResponse, createErrorResponse } from './BaseController'
import database from '../../utils/database'
import { generateId } from '../../mock/utils'

export class SettingsController extends BaseController {
  constructor() {
    super('settings')
  }
  
  /**
   * 获取用户设置
   */
  async getUserSettings() {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT * FROM settings WHERE user_id = ? AND is_deleted = 0',
        ['current_user']
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取用户设置失败')
      }
      
      const data = result.data || []
      const settings: Record<string, any> = {}
      
      data.forEach((item: any) => {
        try {
          settings[item.key] = JSON.parse(item.value)
        } catch (error) {
          settings[item.key] = item.value
        }
      })
      
      return createResponse(settings)
    } catch (error: any) {
      return createErrorResponse(error.message || '获取用户设置失败')
    }
  }
  
  /**
   * 更新用户设置
   */
  async updateUserSettings(settings: Record<string, any>) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      for (const [key, value] of Object.entries(settings)) {
        const stringValue = typeof value === 'string' ? value : JSON.stringify(value)
        
        // 检查设置是否已存在
        const existingResult = await database.query(
          'SELECT id FROM settings WHERE user_id = ? AND key = ? AND is_deleted = 0',
          ['current_user', key]
        )
        
        if (existingResult.code !== 0) {
          continue
        }
        
        const existingData = existingResult.data || []
        
        if (existingData.length > 0) {
          // 更新现有设置
          await database.update(
            'settings',
            {
              value: stringValue,
              updated_at: now
            },
            'user_id = ? AND key = ? AND is_deleted = 0',
            ['current_user', key]
          )
        } else {
          // 创建新设置
          const settingId = generateId()
          await database.insert('settings', {
            id: settingId,
            user_id: 'current_user',
            key: key,
            value: stringValue,
            created_at: now,
            updated_at: now,
            is_deleted: 0
          })
        }
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '更新用户设置失败')
    }
  }
  
  /**
   * 获取单个设置
   */
  async getSetting(key: string) {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT value FROM settings WHERE user_id = ? AND key = ? AND is_deleted = 0',
        ['current_user', key]
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取设置失败')
      }
      
      const data = result.data || []
      if (data.length === 0) {
        return createResponse(null)
      }
      
      const setting = data[0]
      try {
        return createResponse(JSON.parse(setting.value))
      } catch (error) {
        return createResponse(setting.value)
      }
    } catch (error: any) {
      return createErrorResponse(error.message || '获取设置失败')
    }
  }
  
  /**
   * 设置单个配置
   */
  async setSetting(key: string, value: any) {
    try {
      const settings = { [key]: value }
      return await this.updateUserSettings(settings)
    } catch (error: any) {
      return createErrorResponse(error.message || '设置配置失败')
    }
  }
  
  /**
   * 删除设置
   */
  async deleteSetting(key: string) {
    try {
      await ensureDbInit()
      const rowsAffected = await database.update(
        'settings',
        {
          is_deleted: 1,
          updated_at: new Date().toISOString()
        },
        'user_id = ? AND key = ? AND is_deleted = 0',
        ['current_user', key]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('设置不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '删除设置失败')
    }
  }
  
  /**
   * 获取通知设置
   */
  async getNotificationSettings() {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT * FROM notification_settings WHERE user_id = ? AND is_deleted = 0',
        ['current_user']
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取通知设置失败')
      }
      
      const data = result.data || []
      return createResponse(data)
    } catch (error: any) {
      return createErrorResponse(error.message || '获取通知设置失败')
    }
  }
  
  /**
   * 更新通知设置
   */
  async updateNotificationSettings(data: {
    type: string
    enabled: boolean
    sound?: boolean
    vibration?: boolean
    time?: string
  }) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      // 检查通知设置是否已存在
      const existingResult = await database.query(
        'SELECT id FROM notification_settings WHERE user_id = ? AND type = ? AND is_deleted = 0',
        ['current_user', data.type]
      )
      
      if (existingResult.code !== 0) {
        return createErrorResponse(existingResult.message || '查询通知设置失败')
      }
      
      const existingData = existingResult.data || []
      
      if (existingData.length > 0) {
        // 更新现有通知设置
        await database.update(
          'notification_settings',
          {
            enabled: data.enabled ? 1 : 0,
            sound: data.sound ? 1 : 0,
            vibration: data.vibration ? 1 : 0,
            time: data.time || null,
            updated_at: now
          },
          'user_id = ? AND type = ? AND is_deleted = 0',
          ['current_user', data.type]
        )
      } else {
        // 创建新通知设置
        const settingId = generateId()
        await database.insert('notification_settings', {
          id: settingId,
          user_id: 'current_user',
          type: data.type,
          enabled: data.enabled ? 1 : 0,
          sound: data.sound ? 1 : 0,
          vibration: data.vibration ? 1 : 0,
          time: data.time || null,
          created_at: now,
          updated_at: now,
          is_deleted: 0
        })
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '更新通知设置失败')
    }
  }
  
  /**
   * 获取通知列表
   */
  async getNotifications(params: {
    page?: number
    pageSize?: number
    isRead?: boolean
    type?: string
  } = {}) {
    try {
      const { page = 1, pageSize = 20, isRead, type } = params
      
      let whereClause = 'user_id = ? AND is_deleted = 0'
      let whereParams: any[] = ['current_user']
      
      if (isRead !== undefined) {
        whereClause += ' AND is_read = ?'
        whereParams.push(isRead ? 1 : 0)
      }
      
      if (type) {
        whereClause += ' AND type = ?'
        whereParams.push(type)
      }
      
      const result = await database.paginate('notifications', {
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'created_at DESC'
      })
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取通知列表失败')
      }
      
      const paginationData = result.data || {}
      return createResponse({
        list: paginationData.list,
        page: paginationData.page,
        pageSize: paginationData.pageSize,
        total: paginationData.total
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取通知列表失败')
    }
  }
  
  /**
   * 标记通知为已读
   */
  async markNotificationAsRead(id: string) {
    try {
      await ensureDbInit()
      const rowsAffected = await database.update(
        'notifications',
        {
          is_read: 1,
          read_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        },
        'id = ? AND user_id = ? AND is_deleted = 0',
        [id, 'current_user']
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('通知不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '标记通知已读失败')
    }
  }
  
  /**
   * 批量标记通知为已读
   */
  async markAllNotificationsAsRead() {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      await database.update(
        'notifications',
        {
          is_read: 1,
          read_at: now,
          updated_at: now
        },
        'user_id = ? AND is_read = 0 AND is_deleted = 0',
        ['current_user']
      )
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '批量标记通知已读失败')
    }
  }
  
  /**
   * 删除通知
   */
  async deleteNotification(id: string) {
    try {
      await ensureDbInit()
      const rowsAffected = await database.update(
        'notifications',
        {
          is_deleted: 1,
          updated_at: new Date().toISOString()
        },
        'id = ? AND user_id = ? AND is_deleted = 0',
        [id, 'current_user']
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('通知不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '删除通知失败')
    }
  }
  
  /**
   * 获取数据导出状态
   */
  async getDataExportStatus(id: string) {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT * FROM data_exports WHERE id = ? AND user_id = ?',
        [id, 'current_user']
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取导出状态失败')
      }
      
      const data = result.data || []
      if (data.length === 0) {
        return createErrorResponse('导出任务不存在', 1003)
      }
      
      return createResponse(data[0])
    } catch (error: any) {
      return createErrorResponse(error.message || '获取导出状态失败')
    }
  }
  
  /**
   * 创建数据导出任务
   */
  async createDataExport(data: {
    type: string
    format: string
    dateRange?: {
      startDate: string
      endDate: string
    }
    options?: Record<string, any>
  }) {
    try {
      await ensureDbInit()
      const exportId = generateId()
      const now = new Date().toISOString()
      
      const exportData = {
        id: exportId,
        user_id: 'current_user',
        type: data.type,
        format: data.format,
        date_range: data.dateRange ? JSON.stringify(data.dateRange) : null,
        options: data.options ? JSON.stringify(data.options) : null,
        status: 'pending',
        progress: 0,
        file_path: null,
        file_size: 0,
        error_message: null,
        created_at: now,
        updated_at: now
      }
      
      await database.insert('data_exports', exportData)
      
      // 模拟导出过程
      setTimeout(async () => {
        try {
          await database.update(
            'data_exports',
            {
              status: 'processing',
              progress: 50,
              updated_at: new Date().toISOString()
            },
            'id = ?',
            [exportId]
          )
          
          // 再次模拟完成
          setTimeout(async () => {
            try {
              const filePath = `/exports/${exportId}.${data.format}`
              const fileSize = Math.floor(Math.random() * 1000000) + 100000 // 随机文件大小
              
              await database.update(
                'data_exports',
                {
                  status: 'completed',
                  progress: 100,
                  file_path: filePath,
                  file_size: fileSize,
                  updated_at: new Date().toISOString()
                },
                'id = ?',
                [exportId]
              )
            } catch (error) {
              await database.update(
                'data_exports',
                {
                  status: 'failed',
                  error_message: '导出失败',
                  updated_at: new Date().toISOString()
                },
                'id = ?',
                [exportId]
              )
            }
          }, 2000)
        } catch (error) {
          await database.update(
            'data_exports',
            {
              status: 'failed',
              error_message: '导出失败',
              updated_at: new Date().toISOString()
            },
            'id = ?',
            [exportId]
          )
        }
      }, 1000)
      
      return createResponse({
        id: exportId,
        status: 'pending',
        progress: 0
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '创建导出任务失败')
    }
  }
  
  /**
   * 获取数据导入状态
   */
  async getDataImportStatus(id: string) {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT * FROM data_imports WHERE id = ? AND user_id = ?',
        [id, 'current_user']
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取导入状态失败')
      }
      
      const data = result.data || []
      if (data.length === 0) {
        return createErrorResponse('导入任务不存在', 1003)
      }
      
      return createResponse(data[0])
    } catch (error: any) {
      return createErrorResponse(error.message || '获取导入状态失败')
    }
  }
  
  /**
   * 创建数据导入任务
   */
  async createDataImport(data: {
    type: string
    filePath: string
    options?: Record<string, any>
  }) {
    try {
      await ensureDbInit()
      const importId = generateId()
      const now = new Date().toISOString()
      
      const importData = {
        id: importId,
        user_id: 'current_user',
        type: data.type,
        file_path: data.filePath,
        options: data.options ? JSON.stringify(data.options) : null,
        status: 'pending',
        progress: 0,
        imported_count: 0,
        failed_count: 0,
        error_message: null,
        created_at: now,
        updated_at: now
      }
      
      await database.insert('data_imports', importData)
      
      // 模拟导入过程
      setTimeout(async () => {
        try {
          await database.update(
            'data_imports',
            {
              status: 'processing',
              progress: 50,
              updated_at: new Date().toISOString()
            },
            'id = ?',
            [importId]
          )
          
          // 再次模拟完成
          setTimeout(async () => {
            try {
              const importedCount = Math.floor(Math.random() * 100) + 10
              const failedCount = Math.floor(Math.random() * 5)
              
              await database.update(
                'data_imports',
                {
                  status: 'completed',
                  progress: 100,
                  imported_count: importedCount,
                  failed_count: failedCount,
                  updated_at: new Date().toISOString()
                },
                'id = ?',
                [importId]
              )
            } catch (error) {
              await database.update(
                'data_imports',
                {
                  status: 'failed',
                  error_message: '导入失败',
                  updated_at: new Date().toISOString()
                },
                'id = ?',
                [importId]
              )
            }
          }, 2000)
        } catch (error) {
          await database.update(
            'data_imports',
            {
              status: 'failed',
              error_message: '导入失败',
              updated_at: new Date().toISOString()
            },
            'id = ?',
            [importId]
          )
        }
      }, 1000)
      
      return createResponse({
        id: importId,
        status: 'pending',
        progress: 0
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '创建导入任务失败')
    }
  }
  
  /**
   * 重置应用数据
   */
  async resetAppData(options: {
    keepUserData?: boolean
    keepSettings?: boolean
  } = {}) {
    try {
      await ensureDbInit()
      const { keepUserData = false, keepSettings = false } = options
      
      const tables = [
        'habits',
        'habit_records',
        'todos',
        'finance_accounts',
        'finance_transactions',
        'finance_budgets',
        'time_records',
        'time_timers',
        'time_activity_categories'
      ]
      
      if (!keepSettings) {
        tables.push('settings', 'notification_settings')
      }
      
      if (!keepUserData) {
        tables.push('notifications')
      }
      
      for (const table of tables) {
        await database.executeSql(`DELETE FROM ${table} WHERE user_id = ?`, ['current_user'])
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '重置应用数据失败')
    }
  }
}

// 导出单例实例
export const settingsController = new SettingsController()